package com.gcloud.controller.network.timer;

import com.gcloud.controller.network.dao.SubnetDao;
import com.gcloud.controller.network.dao.SubnetDhcpHandleDao;
import com.gcloud.controller.network.entity.Subnet;
import com.gcloud.controller.network.entity.SubnetDhcpHandle;
import com.gcloud.controller.network.util.NeutronSubnetDhcpUtil;
import com.gcloud.core.cache.redis.template.GCloudRedisTemplate;
import com.gcloud.core.quartz.GcloudJobBean;
import com.gcloud.core.quartz.annotation.QuartzTimer;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */
@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@QuartzTimer(fixedDelay = 10 * 1000L)

@Slf4j
public class NeutronSubnetDhcpSycnTimer extends GcloudJobBean {

    @Value("${gcloud.controller.network.subnetDhcpMaxRetry:5}")
    private Integer maxRetry;

    @Autowired
    private SubnetDhcpHandleDao subnetDhcpHandleDao;

    @Autowired
    private GCloudRedisTemplate redisTemplate;

    @Autowired
    private SubnetDao subnetDao;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        List<SubnetDhcpHandle> handles = subnetDhcpHandleDao.runningHandle(maxRetry);

        if(handles == null || handles.isEmpty()){
            return;
        }

        for(SubnetDhcpHandle handle : handles){

            String key = NeutronSubnetDhcpUtil.dhcpRunningKey(handle.getSubnetId());
            String running = redisTemplate.opsForValue().get(key);
            if(running != null){
                continue;
            }

            SubnetDhcpHandle currentHandle = subnetDhcpHandleDao.getById(handle.getSubnetId());
            if(currentHandle.getHandleId() != null && currentHandle.getRetry() < maxRetry){
                Subnet subnet = subnetDao.getById(handle.getSubnetId());
                NeutronSubnetDhcpUtil.createOrUpdateHandle(subnet.getId(), subnet.getProviderRefId());
                subnetDhcpHandleDao.retry(handle.getSubnetId());
            }
        }
    }
}